package chord;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class GUI extends JFrame implements ActionListener
{
    JButton btnExit;
    JButton btnSearch;
    JTextField txtSearch;
    JLabel lblSearch;
    JLabel lblSearchResult;

    Node node;

    public GUI(Node node)
    {
	this.node = node;
    }

    private void createAndShowGUI()
    {
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	lblSearch = new JLabel("Search Key: ");
	this.getContentPane().add(lblSearch);

	txtSearch = new JTextField(20);
	this.getContentPane().add(txtSearch);

	btnSearch = new JButton("Go!");
	this.getContentPane().add(btnSearch);

	btnExit = new JButton("Exit");
	this.getContentPane().add(btnExit);

	lblSearchResult = new JLabel();
	this.getContentPane().add(lblSearchResult);

	this.pack();
	this.setVisible(true);

	btnSearch.addActionListener(this);
	btnExit.addActionListener(this);

	this.setLayout(new FlowLayout());
	this.setSize(500, 200);
	this.setTitle(" Node ID : " + node.intID);
    }

    public void run()
    {
	javax.swing.SwingUtilities.invokeLater(new Runnable()
	{
	    public void run()
	    {
		createAndShowGUI();
	    }
	});
    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {
	if (ae.getSource().equals(btnSearch))
	{
	    int intKeyToSearch;

	    lblSearchResult.setText("Searchiing ...");
	    intKeyToSearch = Integer.parseInt(txtSearch.getText());

	    node.search(intKeyToSearch, true);
	}

	if (ae.getSource().equals(btnExit))
	{
	    node.sendExitMessage();
	}
    }

    public void displaySearchResult(int intNodeID)
    {
	String strText;
	
	if (intNodeID < 0)
	    strText = "Key Not Found";
	else
	    strText = "Key Found at Node : " + intNodeID;
	
	lblSearchResult.setText(strText);
    }
    
    public void displaySearchResult(int intNodeID , SearchMessage msgSearch)
    {
	String strText;
	
	if (intNodeID < 0)
	    strText = "Key Not Found";
	else
	    strText = "Key Found at Node : " + intNodeID;
	
	strText = strText + "  Time Taken ="+  msgSearch.lngNanoTime + " nanoTime.    Message Count =" + msgSearch.intHopCount; 
	Logger.log(LogType.SEARCH_TIME, Long.toString( msgSearch.lngNanoTime ));

	lblSearchResult.setText(strText);
    }
}